import { ref, Ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { sendSMS } from '@/api/login'
import { LoginRequestData } from '@/api/login/types/login'

interface FormState {
  form: LoginRequestData
  isLoading: boolean
  rule: FormRules
  disable: boolean
}
export function useSMS(formState: FormState) {
  const sendSMSLabel: Ref<string> = ref('<span>获取验证码</span>')
  const Countdown = () => {
    let counter = 60
    formState.disable = true
    const intervalId = setInterval(() => {
      if (counter > 0) {
        sendSMSLabel.value = `<span><span style='color:var(--xy-primary-color)'>${counter}</span>秒后重试</span>`
        counter -= 1
      } else {
        sendSMSLabel.value = '<span>获取验证码</span>'
        formState.disable = false
        clearInterval(intervalId)
      }
    }, 1000)
  }

  const handleSendSMS = (formInstance: FormInstance | null) => {
    if (formInstance) {
      formInstance.validateField('phone', (valid: boolean | string) => {
        if (valid === true) {
          sendSMS({
            phone: formState.form.phone
          }).then((res) => {
            if (res.statusCode === '0') {
              ElMessage.success(res.data)
              Countdown()
            }
          })
        }
      })
    }
  }

  return {
    sendSMSLabel,
    handleSendSMS
  }
}
